export const dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	},
	setCacheWithExpire: function(key, data, expireDays = 1) {
		const expireTime = Date.now() + expireDays * 24 * 60 * 60 * 1000;
		const cacheData = {
			data,
			expireTime
		};
		try {
			uni.setStorageSync(key, cacheData);
		} catch (err) {
			console.error('同步缓存失败:', err);
		}
	},
	getCacheWithExpire: function(key) {
		try {
			const cacheData = uni.getStorageSync(key);
			if (!cacheData) return null;

			const {
				data,
				expireTime
			} = cacheData;
			if (expireTime > Date.now()) {
				return data; // 有效数据
			} else {
				uni.removeStorageSync(key); // 过期清理
				return null;
			}
		} catch (err) {
			return null; // 异常返回 null
		}
	},
	debounce(fn, delay = 500) {
		let timer = null;
		return function(...args) {
			if (timer) clearTimeout(timer);
			timer = setTimeout(() => {
				fn.apply(this, args);
			}, delay);
		};
	}
};